package com.jp.knowledge.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.NetLogModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.model.experience.ExperienceModel;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.NetLogUtil;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.view.JpApplicationWebView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/2/25.
 */

public class JpApplicationWebActivity extends SlidingActivity implements JpApplicationWebView.JsCallback {

    // 只允许通过该函数启动该 Activity
    public static void gotoWebActivity(Context context, String url){
        JpApplicationWebView.getInstance(context).openWebActivity(context, url);
    }

    @ViewInject(R.id.web_main_layout)
    private FrameLayout webLayout;
    private String currentPath;
    private JpApplicationWebView applicationWebView;
    private LocalBroadcastManager localBroadcastManager;
    private ClipboardManager clipboardManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_test;
    }

    @Override
    protected void init() {
        currentPath = getIntent().getStringExtra(JpApplicationWebView.WEB_VIEW_CURRENT_PATH);
        // 不允许其他 Activity 通过 startActivity 的方式启动该 Activity
        if(currentPath == null){
            ToasUtil.toast(this, "请使用 gotoWebActivity() 方式打开该 Activity");
            finish();
            return;
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        applicationWebView = application.getApplicationWebView();
        applicationWebView.addJsCallback(this);
//        if(applicationWebView.getParent() != null)
//            ((ViewGroup)applicationWebView.getParent()).removeView(applicationWebView);
//        webLayout.addView(applicationWebView);
    }

    @Override
    protected void onResume() {
        int indexOfWebLayout = webLayout.indexOfChild(applicationWebView);
        if(indexOfWebLayout < 0 || indexOfWebLayout != webLayout.getChildCount()-1) {
            if (applicationWebView.getParent() != null)
                ((ViewGroup) applicationWebView.getParent()).removeView(applicationWebView);
            webLayout.addView(applicationWebView);
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if(currentPath != null && (currentPath.equals("competeTheme/buildTheme")
                || currentPath.equals("follow/companyList")
                || currentPath.equals("follow/productList")
                || currentPath.equals("follow/figureList")
                || currentPath.equals("follow/channelList")))
            localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.GET_ATTION_DATA_BROAD));
        applicationWebView.removeJsCallback(this);
        if(webLayout == applicationWebView.getParent())
            webLayout.removeView(applicationWebView);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && applicationWebView.goBack())
            return true;
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onJsCallback(JsonObject obj) {
        try {
            switch (obj.get("type").getAsString()) {
                case "toNative":                    // 切换回原生
                    JsCallbackHandle.ToNative.handle(this, obj);
                    break;
                case "postUserDataToNative":       // H5 端登陆成功
                    JsCallbackHandle.PostUserDataToNative.handle(this, obj);
                    break;
                case "toLibraryDetail":             // 跳到详情
                    JsCallbackHandle.ToLibraryDetail.handle(this, obj);
                    break;
                case "toSearch":                    // 跳到搜索
                    JsCallbackHandle.ToSearch.handle(this, obj);
                    break;
                case "toggleTime":                  // 隐藏/显示 时间栏
                    JsCallbackHandle.ToggleTime.handle(this, obj);
                    break;
                case "openWebView":                 // 打开内置浏览器
                    JsCallbackHandle.OpenWebView.handle(this, obj);
                    break;
                case "shujutext":                   // 保存网络信息数据
                    JsCallbackHandle.ShuJuText.handle(this, obj);
                    break;
                case "updateLightExp":              // 添加体验数据
                    JsCallbackHandle.UpdateLightExp.handle(this, obj);
                    break;
                case "share":                       // 分享
                    JsCallbackHandle.Share.handle(this, obj);
                    break;
            }
        } catch (Exception e){
            L.e(e.toString());
        }
        return false;
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                ToasUtil.toast(mContext, platform + "收藏成功啦");
            } else {
                ToasUtil.toast(mContext, platform + "分享成功啦");
            }
        }
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToasUtil.toast(mContext, platform + "分享失败啦");
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToasUtil.toast(mContext, platform + "分享取消了");
        }
    };
    /* 策略枚举 */
    private enum JsCallbackHandle{
        /* 切换回原生 */
        ToNative(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                activity.finish();
            }
        },
        /* H5 端登陆成功 */
        PostUserDataToNative(){
            @Override
            public void handle(JpApplicationWebActivity activity,JsonObject obj) {
                try {
                    UserData userData = JsonUtil.getInstance()
                            .jsonToObject(obj.get("param").getAsJsonObject(), UserData.class);
                    if (userData != null && userData.getIsLogin() == 1) {
                        activity.application.setUserData(userData);
                        Intent intent = new Intent();
                        intent.setAction(LocalBroadCast.GET_LOGIN_INFO);
                        activity.localBroadcastManager.sendBroadcast(intent);
                        HttpHelper.token = userData.getToken();
                        HttpHelper.uuid = userData.getUuid();
                        SharedUtil.getInstance(activity.mContext)
                                .saveTokenAndUUId(HttpHelper.token, HttpHelper.uuid);
                    }
                } catch (Exception e) {
                    L.e("更新用户信息到原生失败");
                }
            }
        },
        /* 跳到详情 */
        ToLibraryDetail(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                activity.startActivity(new Intent(activity, InfoDataDetailActivity.class)
                        .putExtra("webParam", obj.get("param").getAsJsonObject().toString()));
//                activity.applicationWebView.setCurrentPath("content");
            }
        },
        /* 跳到搜索 */
        ToSearch(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                SearchSimpleActivity.gotoSearch(activity, obj.get("param").getAsJsonObject().toString());
//                activity.applicationWebView.setCurrentPath("search");
            }
        },
        /* 隐藏/显示 时间栏 */
        ToggleTime(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                if(obj.get("param").getAsInt() == 1) {
                    activity.webLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_FULLSCREEN);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                        activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
                } else {
                    activity.webLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                        activity.getWindow().setStatusBarColor(activity.getResources().getColor(R.color.theme_color));
                }
            }
        },
        /* 打开内置浏览器 */
        OpenWebView(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                WebBrowserActivity.openWebActivity(activity, obj.get("param").getAsString());
            }
        },
        /* 保存网络信息数据 */
        ShuJuText(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                NetLogModel netLogModel = new NetLogModel();
                try {
                    JsonObject param = obj.get("param").getAsJsonObject();
                    netLogModel.setType(param.get("type").getAsString());
                    netLogModel.setRequestTime(param.get("strtime").getAsString());
                    netLogModel.setResponseTime(param.get("endtime").getAsString());
                    netLogModel.setUrl(param.get("url").getAsString());
                    netLogModel.setRequestParam(param.get("param").getAsJsonObject().toString());
                    netLogModel.setErrorCode(Integer.parseInt(param.get("errCode").getAsString()));
                    netLogModel.setMessage(param.get("message").getAsJsonObject().toString());
                } catch (Exception e){} finally {
                    NetLogUtil.saveNetMsgToLocal(netLogModel);
                }
            }
        },
        /* 添加体验数据 */
        UpdateLightExp(){
            @Override
            public void handle(JpApplicationWebActivity activity, JsonObject obj) {
                JsonObject param = obj.get("param").getAsJsonObject().get("apps").getAsJsonObject();
                ExperienceModel experienceModel = JsonUtil.getInstance().jsonToObject(param, ExperienceModel.class);
                List<ExperienceModel> experienceModels = new ArrayList<>();
                experienceModels.add(experienceModel);

                Intent intent = new Intent(LocalBroadCast.ADD_EXP_APP);
                intent.putExtra("appData", (Serializable) experienceModels);
                intent.putExtra("gid", obj.get("param").getAsJsonObject().get("gid").getAsString());
                activity.localBroadcastManager.sendBroadcast(intent);
            }
        },
        /* 分享 */
        Share(){
            @Override
            public void handle(final JpApplicationWebActivity activity, JsonObject obj) {
                final JsonObject param = obj.get("param").getAsJsonObject();
                final String title = param.get("title").getAsString();
                final String image = param.get("image").getAsString();
                String dest = param.get("desc").getAsString();
                final String url = param.get("url").getAsString();
                new ShareAction(activity)
                        .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .addButton("share_copy_url", "share_copy_url", "ttoutiaofuzhilianjie", "ttoutiaofuzhilianjie")
                        .setShareboardclickCallback(new ShareBoardlistener() {
                            @Override
                            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                                L.e("ShareAction", "share_media=" + share_media);
                                if (snsPlatform.mShowWord.equals("umeng_sharebutton_custom")) {
                                    ToasUtil.toast(activity, "自定义按钮");
                                } else if(snsPlatform.mShowWord.equals("share_copy_url")){
                                    if(param != null){
                                        StringBuilder copyContent = new StringBuilder();
                                        if(title != null && title.trim().length() > 0)
                                            copyContent.append("【" + title + "】 ");
                                        if(url != null && url.length() > 0)
                                            activity.clipboardManager.setText(copyContent.append(url));
                                        ToasUtil.toast(activity, "复制成功");
                                    }else {
                                        ToasUtil.toast(activity, "没有内容可复制!");
                                    }
                                }else {
                                    if(param != null) {
                                        ShareAction shareAction = new ShareAction(activity)
                                                .withTitle("竞品说").setPlatform(share_media)
                                                .setCallback(activity.umShareListener);
                                        if(title != null && title.trim().length() > 0)
                                            shareAction.withText(title);
                                        if(url != null && url.length() > 0)
                                            shareAction.withTargetUrl(url);
                                        try {
                                            if (image != null && image.trim().length() > 0)
                                                shareAction.withMedia(new UMImage(activity, image));
                                        } catch (Exception e){} finally {
                                            shareAction.share();
                                        }
                                    }else{
                                        ToasUtil.toast(activity, "没有内容可分享!");
                                    }
                                }
                            }
                        }).open();
            }
        };
        public abstract void handle(JpApplicationWebActivity activity, JsonObject obj);
    }
}
